package Bank;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.security.GeneralSecurityException;

public class P7Verify {
	public static void main(String[] args) throws GeneralSecurityException,
			IOException {
		if ((args.length < 2) || (args.length > 5)) {
			System.out
					.println("Usage: \nP7Verify rootcertfile signaturefile [inputfile] [dn]\n");

			System.exit(-1);
		}
		if ("-debug".equals(args[(args.length - 1)]))
			PKCS7Tool.setDebug(true);
		PKCS7Tool tool = PKCS7Tool.getVerifier(args[0]);

		InputStream in = System.in;
		FileInputStream signin = null;
		try {
			signin = new FileInputStream(args[1]);
			String signature = new String(readData(signin));

			if (args.length > 2) {
				in = new FileInputStream(args[2]);
			}
			byte[] data = readData(in);

			String dn = null;
			if (args.length > 3) {
				dn = args[3];
			}
			tool.verify(signature, data, dn);
		} finally {
			if ((in != null) && (System.in != in))
				in.close();
			if (signin != null)
				signin.close();
		}
		System.out.println("[VERIFY OK]");
	}

	private static byte[] readData(InputStream in) throws IOException {
		ByteArrayOutputStream bai = new ByteArrayOutputStream();
		byte[] buf = new byte[256];
		int len;
		while ((len = in.read(buf)) > 0) {
			bai.write(buf, 0, len);
		}
		return bai.toByteArray();
	}
}